package mercurius.fitness.client.util;

import java.util.Comparator;

import net.pleso.framework.client.dal.IDataColumn;
import net.pleso.framework.client.dal.IDataRow;
import net.pleso.framework.client.dal.db.types.DBInteger;

public class DataRowComparator implements Comparator {
	
	private String orderByColumnName;
	private boolean orderByDirection; // true - "asc"; false - "desc"
	private IDataColumn sortColumn = null;
	private boolean firstCompare = true;
	
	public DataRowComparator(String orderByColumnName, boolean orderByDirection) {
		this.orderByColumnName = orderByColumnName;
		this.orderByDirection = orderByDirection;
	}

	public int compare(Object o1, Object o2) {
		IDataRow row1 = (IDataRow) o1;
		IDataRow row2 = (IDataRow) o2;
		
		if (row1 == null && row2 != null)
			return -1;
		if (row2 == null && row1 != null)
			return 1;
		if (row2 == null && row1 == null)
			return 0;
		
		if (this.firstCompare) {
			this.sortColumn = getSortColumnIndex(row1);
			this.firstCompare = false;
		}
		
		if (this.sortColumn == null)
			return 0;
		
		int c = 0;
		
		if (row1.getCell(sortColumn) instanceof DBInteger && row2.getCell(sortColumn) instanceof DBInteger) {
			c = ((DBInteger)row1.getCell(sortColumn)).getInteger().compareTo(((DBInteger)row2.getCell(sortColumn)).getInteger());
		} else {
			c = row1.getCell(sortColumn).getValue().compareTo(row2.getCell(sortColumn).getValue());
		}
			
		if (!orderByDirection)
			return -c;
		else
			return c;
	}
	
	public IDataColumn getSortColumnIndex(IDataRow row) {
		for(int i = 0; i < row.getColumnCount(); i++) {
			IDataColumn dataColumn = row.getColumn(i);
			if (dataColumn.getName().equalsIgnoreCase(orderByColumnName))
				return dataColumn;
		}
		return null;
	}
	
}
